package util

// 后台工具方法

import (
	"crypto/md5"
	"encoding/hex"
	"strconv"

	"github.com/casbin/casbin"
	"github.com/gin-contrib/sessions"

	"github.com/gin-gonic/gin"
	"github.com/xormplus/xorm"
)

//md5加密方法
func Md5Pwd(pwd string) string {
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(pwd + Md5Salt))
	cipherStr := md5Ctx.Sum(nil)
	return hex.EncodeToString(cipherStr)
}

//从gin context获取db连接
func GetDb(c *gin.Context) *xorm.Engine {
	engine := c.MustGet(DatabaseEngine).(*xorm.Engine)
	return engine
}

//从gin context获取casbin enforcer
func GetCasbin(c *gin.Context) *casbin.Enforcer {
	ce := c.MustGet(CasbinEnforcer).(*casbin.Enforcer)
	return ce
}

//获取页面的分页参数
func GetPageParam(c *gin.Context) *Page {
	var p = new(Page)
	var cPage = c.DefaultQuery("_cpage", "1")
	var pSize = c.DefaultQuery("_psize", "")
	p.CurrentPage, _ = strconv.Atoi(cPage)
	p.Qstr = c.Request.RequestURI
	if pSize != "" {
		p.PageSize, _ = strconv.Atoi(pSize)
	}
	return p
}

//获取当前上下文中的session
func GetSession(c *gin.Context) sessions.Session {
	session := sessions.Default(c)
	return session
}

//获取当前登录用户
func GetCurrLoginUser(c *gin.Context) string {
	username := GetSession(c).Get(LoginAccountName)
	if username == nil {
		return ""
	}
	return username.(string)
}

//获取当前登录用户ID
func GetCurrLoginUID(c *gin.Context) int64 {
	loginuid := GetSession(c).Get(LoginAccountID)
	if loginuid == nil {
		return 0
	}
	return loginuid.(int64)
}

//删除当前session
func RemoveLoginSession(c *gin.Context) {
	session := GetSession(c)
	session.Delete(LoginAccountName)
	session.Delete(LoginAccountID)
	session.Clear()
	session.Save()
	return
}
